import 'dart:math';

import 'package:flutter/material.dart';

class ExpandStateBean{
  bool isOpen;
  int index;
  ExpandStateBean( this.index, this.isOpen);
}

class ExpansionPanelListDemo extends StatefulWidget {
  const ExpansionPanelListDemo({Key? key}) : super(key: key);

  @override
  _ExpansionPanelListDemoState createState() => _ExpansionPanelListDemoState();
}

class _ExpansionPanelListDemoState extends State<ExpansionPanelListDemo> {
  int currentIndex = -1;
  List<ExpandStateBean> expandStateList = [];
  //构造方法，调用这个类的时候自动执行
  _ExpansionPanelListDemoState() {
    //便利为两个List进行赋值
    for(int i=0;i<10;i++){
      expandStateList.add(ExpandStateBean(i,false));
    }
  }
  _setCurrentIndex(index,bol) {
    setState(() {
      //遍历可展开状态列表
      expandStateList.forEach((item){
        if(item.index==index){
          //取反，经典取反方法
          item.isOpen = !bol;
        }
      });
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('展开关闭列表'),
      ),
      body: SingleChildScrollView( // 必须放在可滚动的组件里
        child: ExpansionPanelList(
          expansionCallback: (i, bol) {
            //调用内部方法
            _setCurrentIndex(i, bol);
          },
          children:
            expandStateList.map((item) {
              return ExpansionPanel(
                headerBuilder: (context, isExpanded) {
                  return ListTile(
                    title: Text('This is No. ${item.index}'),
                  );
                },
                body: ListTile(
                  title:Text('expansion no.${item.index}')
                ),
                isExpanded: item.isOpen
              );
            }).toList(),
        ),

      ) ,
    );
  }
}

